package com.linhngua.code.gwt.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.linhngua.code.gwt.shared.Entity;

public class Main implements EntryPoint {

	private RemoteInvocationAsync remoteInvocationAsync = GWT
			.create(RemoteInvocation.class);

	private Label label;

	private boolean alreadyPrompt;

	public void onModuleLoad() {

		RootPanel rootPanel = RootPanel.get("main");
		label = new Label();

		rootPanel.add(label, 100, 100);
		refreshRequestList();
		// fire a timer
		Timer refreshTimer = new Timer() {

			@Override
			public void run() {

				refreshRequestList();

			}
		};

		refreshTimer.scheduleRepeating(15000);

		// handle error

		GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {

			public void onUncaughtException(Throwable t) {
				if (!alreadyPrompt) {
					StringBuilder builder = new StringBuilder();
					for (StackTraceElement e : t.getStackTrace()) {
						builder.append(e.toString());
					}

					Window.prompt("Error", builder.toString());
					alreadyPrompt = true;
				}

			}

		});
	}

	protected void refreshRequestList() {
		remoteInvocationAsync.getEntity(new AsyncCallback<Entity>() {

			public void onSuccess(Entity entity) {
				label.setText(entity.getName());

			}

			public void onFailure(Throwable t) {
				StringBuilder builder = new StringBuilder();
				for (StackTraceElement e : t.getStackTrace()) {
					builder.append(e.toString());
				}

				Window.prompt("Remote Invocation Error", builder.toString());
			}
		});

	}

}
